package edu.tgc.web.controller.system;

import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

import org.abyss.common.web.controller.easyui.tree.CommonCrudEasyUiTreeController;
import org.abyss.common.web.controller.easyui.tree.EasyUiTreeEntityMapBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;

import edu.tgc.entity.system.SysDuty;
import edu.tgc.entity.system.SysPosition;
import edu.tgc.service.system.SysPositionService;
import edu.tgc.web.form.system.SysDutyForm;

@Controller
@RequestMapping(value = "sys/duty")
public class SysDutyController extends CommonCrudEasyUiTreeController<SysDuty, UUID, SysDutyForm> {

    @Autowired
    protected SysPositionService sysPositionService;

    @Override
    protected void buildIgnoreProperties(Collection<String> ignoreProperties) {
        ignoreProperties.add("codePath");
        ignoreProperties.add("childrens");
        ignoreProperties.add("positions");
    }

    @Override
    protected EasyUiTreeEntityMapBuilder<SysDuty> getTreeGridEntityMapBuilder(SysDutyForm form) {
        final Set<SysDuty> checkedList = new HashSet<>();
        String ids = form.getJoinIds();
        if (StringUtils.hasText(ids)) {
            for (String id : ids.split(",")) {
                SysPosition entity = this.sysPositionService.getById(UUID.fromString(id));
                if (entity != null) {
                    checkedList.addAll(entity.getDuties());
                }
            }
        }

        return new EasyUiTreeEntityMapBuilder<SysDuty>() {
            @Override
            public void build(Map<String, Object> entityMap, SysDuty entity, List<SysDuty> children) {
                if (checkedList.size() != 0 && checkedList.contains(entity)) {
                    entityMap.put("selected", true);
                }
                if ("function".equals(entity.getType().getCode())) {
                    entityMap.put("iconCls", "icon-key");
                }
                entityMap.put("id", entity.getId());
                entityMap.put("code", entity.getCode());
                entityMap.put("codePath", entity.getCodePath());
                entityMap.put("name", entity.getName());
                entityMap.put("description", entity.getDescription());
                entityMap.put("type", entity.getType());
                entityMap.put("sort", entity.getSort());
                entityMap.put("enabled", entity.getEnabled());
                entityMap.put("createTime", entity.getCreateTime());
                entityMap.put("lastModifyTime", entity.getLastModifyTime());
            }
        };
    }

}
